
#include <stdio.h>


int SizeOfFile(char *FileName)
{
	FILE *file;
	file = fopen(FileName, "r");
	int sz = 0;

	if(file)
	{
		int prev = ftell(file);
		fseek(file, 0L, SEEK_END);
		sz = ftell(file);
		fclose(file);
	}
    return sz;
}


char* ReadFile(char *FileName)
{
	FILE *file;
	file = fopen(FileName, "r");

	char *DataF;

	if (file) 
	{
		int lenght = SizeOfFile(FileName);
		DataF = new char[lenght + 1];
		DataF[lenght] = 0;

		int i = 0;
		while(DataF[i] != NULL)
		{
			DataF[i] = 0;
			i++;
		}

		fread(DataF, 1, lenght, file);
		fclose(file);
	}
	return DataF;
}

 
void WriteFile(char *DestinationFile, char *dataSouce)
{
	FILE *file;
	file = fopen(DestinationFile, "w");

	if(file)
	{
		fprintf(file, "%s", dataSouce);
	}
	fclose(file);
}


int Length(char *a)
{
	int i = 0;
	while(a[i] != NULL)
		i++;
	return i;
}


char* Compress(char *Data)
{	
	int length = Length(Data);
	int SizeCompress = 0;

	for(int i = 0; i < length; i++)
	{
		if(Data[i] != Data[i + 1])
		{
			SizeCompress += 2;
		}
	}

	char *DataCompress = new char[SizeCompress + 1];
	DataCompress[SizeCompress] = 0;
	int x = 0;
	while(DataCompress[x] != NULL)
	{
		DataCompress[x] = 0;
		x++;
	}

	int count = 1;
	int t = 0;
	for(int i = 0; i < length; i++)
	{
		char current = Data[i];
		while(current == Data[i + 1])
		{
			count++;
			i++;
		}
		DataCompress[t] = count;
		DataCompress[t + 1] = current;
		count = 1;
		t = t + 2;
	}

	delete []Data;
	return DataCompress;
}


char* Extract(char *Data)
{
	int length = Length(Data);

	int SizeExtract = 0;
	for(int i = 0; i < length; i += 2)
	{
		SizeExtract += Data[i];
	}

	char *DataExtract = new char[SizeExtract + 1];
	DataExtract[SizeExtract] = 0;
	int x = 0;
	while(DataExtract[x] != NULL)
	{
		DataExtract[x] = 0;
		x++;
	}

	x = 0;
	for(int i = 0; i < length; i += 2)
	{
		int j;
		for(j = 0; j < Data[i]; j++)
		{
			DataExtract[x] = Data[i + 1];
			x++;
		}
	}
	return DataExtract;
}


int main()
{
	char *a = Compress(ReadFile("Test.txt"));
	WriteFile("Compressed.txt", a);
	char *b = Extract(ReadFile("Compressed.txt"));
	WriteFile("Extracted.txt", b);
	delete []a;
	delete []b;
	return 0;
}